/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.base.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreCardTemplateProduct;
import com.chlitina.store.modules.base.entity.StoreCardTemplateProductDetail;
import com.chlitina.store.modules.base.entity.StoreCardTemplateTimes;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.entity.StoreSelfProduct;
import com.chlitina.store.modules.base.service.StoreCardTemplateProductDetailService;
import com.chlitina.store.modules.base.service.StoreCardTemplateProductService;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.expert.entity.Product;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 产品充值卡模板Controller
 * @author liujiang
 * @version 2013-11-03
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/base/storeCardTemplateProduct")
public class StoreCardTemplateProductController extends BaseController {

	@Autowired
	private StoreCardTemplateProductService storeCardTemplateProductService;
	@Autowired
	private StoreCardTemplateProductDetailService storeCardTemplateProductDetailService;
	@Autowired
	private StoreProductService storeProductService;
	
	@ModelAttribute
	public StoreCardTemplateProduct get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeCardTemplateProductService.get(id);
		}else{
			return new StoreCardTemplateProduct();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(required=false)String currentSelectId, StoreCardTemplateProduct storeCardTemplateProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		String searchStatus = request.getParameter("searchStatus");
        Page<StoreCardTemplateProduct> page = storeCardTemplateProductService.find(new Page<StoreCardTemplateProduct>(request, response), storeCardTemplateProduct, searchStatus); 
        model.addAttribute("searchStatus", searchStatus);
        model.addAttribute("page", page);
        Map<Long, List<String>> map = Maps.newHashMap();
        for(StoreCardTemplateProduct s :  page.getList()) {
        	List<String> list = Lists.newArrayList();
        	for (StoreCardTemplateProductDetail sd : storeCardTemplateProductDetailService.findBy(s)) {
        		StoreProduct storeProduct = sd.getStoreProduct();
    			if(storeProduct.getProduct_type() == StoreProduct.TYPE_SYS) {
    				Product product = storeProduct.getProduct();
    				list.add(product.getName());
    			} else {
    				StoreSelfProduct product = storeProduct.getStoreSelfProduct();
    				list.add(product.getName());
    			}
        	}
        	map.put(s.getId(), list);
        }
        model.addAttribute("productMap", map);
    	model.addAttribute("currentSelectId", currentSelectId);
		return "modules/base/storeCardTemplateProductList";
	}

	@RequestMapping(value = "form")
	public String form(StoreCardTemplateProduct storeCardTemplateProduct, Model model) {
		Map<Long, String> productMap = Maps.newLinkedHashMap();
		if(storeCardTemplateProduct.getId() != null) {
			List<StoreCardTemplateProductDetail> productList = storeCardTemplateProductDetailService.findBy(storeCardTemplateProduct);
			for (StoreCardTemplateProductDetail storeCardTemplateProductDetail : productList) {
				StoreProduct storeProduct = storeCardTemplateProductDetail.getStoreProduct();
				if(storeProduct.getProduct_type() == StoreProduct.TYPE_SYS) {
					Product product = storeProduct.getProduct();
					productMap.put(storeProduct.getId(), product.getName());
				} else {
					StoreSelfProduct product = storeProduct.getStoreSelfProduct();
					productMap.put(storeProduct.getId(), product.getName());
				}
				
			}
		}
		model.addAttribute("productMap", productMap);
		model.addAttribute("storeCardTemplateProduct", storeCardTemplateProduct);
		return "modules/base/storeCardTemplateProductForm";
	}

	@RequestMapping(value = "save")
	public String save(String pageNo, String productIds, StoreCardTemplateProduct storeCardTemplateProduct, Model model, RedirectAttributes redirectAttributes) {
		Store store = StoreUtils.getStore();
		storeCardTemplateProduct.setStore(store);
		storeCardTemplateProduct.setDiscount(storeCardTemplateProduct.getDiscount()/100);
		if (!beanValidator(model, storeCardTemplateProduct)){
			return form(storeCardTemplateProduct, model);
		}
		storeCardTemplateProductService.save(storeCardTemplateProduct);
		
		List<Long> saveIds = Lists.newArrayList();
		String [] productList = productIds.split(",");
		for (int i = 0; i < productList.length; i++) {
			String id = productList[i];
			if (StringUtils.isNotEmpty(id)){
				long productId = Long.parseLong(id);
				saveIds.add(productId);
			}
		}
		List<Long> existIds = Lists.newArrayList();
		List<StoreCardTemplateProductDetail> detailList = storeCardTemplateProduct.getProductList();
		for (StoreCardTemplateProductDetail detail : detailList) {
			existIds.add(detail.getStoreProduct().getId());
		}
		List<Long> deleteIds = Lists.newArrayList();
		for (Long id : existIds) {
			if(!saveIds.contains(id)){
				deleteIds.add(id);
			}
		}
		List<Long> addIds = Lists.newArrayList();
		for (Long id : saveIds) {
			if(!existIds.contains(id)){
				addIds.add(id);
			}
		}
		for (Long id : addIds) {
			StoreCardTemplateProductDetail detail = new StoreCardTemplateProductDetail();
			detail.setStoreCardTemplateProduct(storeCardTemplateProduct);
			detail.setStoreProduct(storeProductService.get(id));
			storeCardTemplateProductDetailService.save(detail);
		}
		for (Long id : deleteIds) {
			storeCardTemplateProductDetailService.delete(storeCardTemplateProduct.getId(), id);
		}
		addMessage(redirectAttributes, "保存产品充值卡模板'" + storeCardTemplateProduct.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/base/storeCardTemplateProduct/?pageNo=" + pageNo +"&currentSelectId=" + storeCardTemplateProduct.getId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(StoreCardTemplateProduct storeCardTemplateProduct, RedirectAttributes redirectAttributes) {
		int status = storeCardTemplateProduct.getStatus();
		if (status == StoreCardTemplateProduct.FLAG_ENABLE) {
			storeCardTemplateProduct.setStatus(StoreCardTemplateProduct.FLAG_DISABLE);
		} else {
			storeCardTemplateProduct.setStatus(StoreCardTemplateProduct.FLAG_ENABLE);
		}
		storeCardTemplateProductService.save(storeCardTemplateProduct);
		addMessage(redirectAttributes, "产品充值卡模板状态更改成功！");
		return "redirect:"+Global.ADMIN_PATH+"/base/storeCardTemplateProduct/";
	}

}
